<template>
  <div class="dashboard">
    <!-- 欢迎卡片 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>欢迎来到物业管理系统</span>
          </div>
          <div class="welcome-message">
            <p>您好，{{ user.name }}！</p>
            <p>您可以通过左侧导航菜单管理系统的各项功能。</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 统计信息卡片 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>总用户数</span>
          </div>
          <div>
            <el-statistic :value="totalUsers" suffix="人" />
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>总建筑物数</span>
          </div>
          <div>
            <el-statistic :value="totalBuildings" suffix="栋" />
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>总单元数</span>
          </div>
          <div>
            <el-statistic :value="totalUnits" suffix="个" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 房间空闲情况卡片 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>房间空闲情况</span>
          </div>
          <div>
            <el-statistic
              :title="'空闲房间数'"
              :value="roomStatus.free"
              suffix="间"
            ></el-statistic>
            <el-progress
              :percentage="roomStatus.freePercentage"
              status="success"
              style="margin: 20px 0"
            />
            <p>总房间数: {{ roomStatus.total }}</p>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from "axios";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

export default {
  name: "Dashboard",
  setup() {
    const user = ref({
      name: "用户",
    });

    const totalUsers = ref(0);
    const totalBuildings = ref(0);
    const totalUnits = ref(0);
    const roomStatus = ref({
      free: 0,
      total: 0,
      freePercentage: 0,
    });
    const router = useRouter();

    // 获取用户信息
    const fetchUserData = async () => {
      try {
        const token = localStorage.getItem("token");
        const response = await axios.get("http://localhost:3008/users/me", {
          headers: { Authorization: `Bearer ${token}` },
        });
        if (response.data && response.data.data) {
          user.value = response.data.data;
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        ElMessage.error("获取用户信息失败，请重新登录");
        // 跳转到登录页面
        router.push("/login");
      }
    };

    // 获取统计数据
    const fetchStatistics = async () => {
      try {
        const token = localStorage.getItem("token");

        // 获取建筑物列表
        const buildingsResponse = await axios.get(
          "http://localhost:3008/buildings",
          {
            headers: { Authorization: `Bearer ${token}` },
          }
        );

        // 获取用户数
        const usersResponse = await axios.get("http://localhost:3008/users", {
          headers: { Authorization: `Bearer ${token}` },
        });

        // 获取单元数
        const unitsResponse = await axios.get("http://localhost:3008/units", {
          headers: { Authorization: `Bearer ${token}` },
        });

        if (
          buildingsResponse.data &&
          usersResponse.data &&
          unitsResponse.data
        ) {
          totalBuildings.value = buildingsResponse.data.data.length; 
          totalUsers.value = usersResponse.data.data.length; 
          totalUnits.value = unitsResponse.data.data.length; 
        }
      } catch (error) {
        console.error("获取统计数据失败:", error);
        ElMessage.error("获取统计数据失败，请稍后再试");
      }
    };

    // 获取房间空闲情况
    const fetchRoomStatus = async () => {
      try {
        const token = localStorage.getItem("token");
        const response = await axios.get("http://localhost:3008/rooms/status", {
          headers: { Authorization: `Bearer ${token}` },
        });
        if (response.data && response.data.data) {
          roomStatus.value = response.data.data;
          roomStatus.value.freePercentage = roomStatus.value.total
            ? ((roomStatus.value.free / roomStatus.value.total) * 100).toFixed(
                2
              )
            : 0;
        }
      } catch (error) {
        console.error("获取房间状态失败:", error);
        ElMessage.error("获取房间状态失败，请稍后再试");
      }
    };

    onMounted(() => {
      fetchUserData();
      fetchStatistics();
      fetchRoomStatus();
    });

    return {
      user,
      totalUsers,
      totalBuildings,
      totalUnits,
      roomStatus,
    };
  },
};
</script>

<style scoped>
.box-card {
  width: 100%;
}

.mt-4 {
  margin-top: 1.5rem;
}

.welcome-message {
  margin-top: 20px;
  font-size: 16px;
  color: #606266;
}

.stat-title {
  font-size: 16px;
  color: #606266;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  margin-top: 10px;
}

/* 响应式调整 */
@media (max-width: 767px) {
  .box-card {
    margin-bottom: 20px;
  }
}
</style>
